package com.acme.bankapp.service.bank;

import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;

import com.acme.bankapp.domain.bank.Account;
import com.acme.bankapp.domain.bank.Bank;
import com.acme.bankapp.domain.bank.CheckingAccount;
import com.acme.bankapp.domain.bank.Client;

/**
 * Class {@code BankReport} is used to obtain statistics.
 * @author Artem Nikitin
 *
 */
public class BankReport {
	public int getNumberOfCustomers(Bank bank) {
		return bank.getClientCount();
	}
	
	public int getNumberOfAccounts(Bank bank) {
		int nAccounts = 0;
		for (Client client : bank.getClients()) {
			nAccounts += client.getAcountsCount();
		}
		return nAccounts;
	}
	
	public Set<Account> getAccountsSortedBySum(Bank bank) {
		Set<Account> accounts = new TreeSet<>(new Comparator<Account>() {
			@Override
			public int compare(Account o1, Account o2) {
				if (o1.equals(o2)) 
					return 0;
				if (o1.getBalance() > o2.getBalance()) 
					return 1;
				else if (o1.getBalance() < o2.getBalance()) {
					return -1;
				}
				return 0;
			}
		});
		
		for (Client client : bank.getClients()) {
			accounts.addAll(client.getAccounts());
		}
		
		return accounts;
	}
	
	public double getBankCredit(Bank bank) {
		double credit = 0;
		for (Client client : bank.getClients()) {
			for (Account account : client.getAccounts()) {
				if (account instanceof CheckingAccount) {
					credit += ((CheckingAccount) account).getOverdraft();
				}
			}
		}
		
		return credit;
	}
	
	public Map<Client, Set<Account>> getCustomerAccount(Bank bank) {
		Map<Client, Set<Account>> cliAccounts = new HashMap<>();
		for (Client client : bank.getClients()) {
			cliAccounts.put(client, client.getAccounts());
		}
		
		return cliAccounts;
	}
}